package main

import (
	"flag"
	"os/exec"
	"path"
	"bytes"

	"ddns/getip"
	dns "ddns/huaweiclouddns"
	log "ddns/log"
	"ddns/processjson"
	"time"

	"github.com/sirupsen/logrus"
	lumberjack "gopkg.in/natefinch/lumberjack.v2"
)

func main() {
	cfg := flag.String("config", "config/ddns.json", "Plase input the config file")
	// 读取配置文件
	flag.Parse()

	// 行解析json
	conf, err := processjson.LoadConfig(*cfg)
	if err != nil {
		log.Errorf("err: %v", err)
		return
	}

	log.Debugf("config: %v", *cfg)
	level, err := logrus.ParseLevel(conf.LogLevel)
	// case "panic":
	// 	return PanicLevel, nil
	// case "fatal":
	// 	return FatalLevel, nil
	// case "error":
	// 	return ErrorLevel, nil
	// case "warn", "warning":
	// 	return WarnLevel, nil
	// case "info":
	// 	return InfoLevel, nil
	// case "debug":
	// 	return DebugLevel, nil
	// case "trace":
	// 	return TraceLevel, nil
	if err != nil {
		log.Errorf("parse cfg logrus level failed, %v", err)
		log.SetLevel(logrus.DebugLevel)
	} else {
		log.SetLevel(level)
	}

	if conf.LogMode == 0 {
		logger_name := "hwddns.log"

		logFileName := path.Join(conf.LogPath, logger_name)
                log.SetOutPut(&lumberjack.Logger{
		    Filename: logFileName,
		    MaxSize:    conf.LogSize, // megabytes
                    MaxAge:     conf.LogDay, //days
                    Compress:   true, // disabled by default
		})
	}

	log.Infof("load config success,config: %+v", conf)
	// client := parameter.NewClient(conf.DomainCfg)
	myip, err := getip.Process(*&conf.GetIps)
	if err != nil {
		log.Errorf("Get the public IP err: %v", err)
	} else {
		log.Infof("Get public ip success, IP: %+v", myip)
	}
	ips := []string{myip}

	// 如果第一次启动就执行，则直接获取ip(记录ip)，并修改dns信息
	if conf.IsFirstModify {
		log.Infof("perform a check at startup")
		err = dns.DoneUp(conf, ips)
		if err != nil {
			log.Errorf("The first time to execute dns to check and modify job errors , %v", err)
		} else if conf.OtherScript != "" {
                        cmd := exec.Command(conf.OtherScript, ips[0])
                        var out bytes.Buffer
                        var stderr bytes.Buffer
                        var input bytes.Buffer
                        cmd.Stdout = &out
                        cmd.Stderr = &stderr
			cmd.Stdin = &input
                        err = cmd.Run()
			log.Infoln("args: ", cmd.Args)
			log.Infoln("out: ",out.String())
			log.Infoln("input: ",input.String())
			log.Infoln("stderr: ",stderr.String())
			// cmd, err := exec.Command(conf.OtherScript, ips[0]).Output()
			// if err != nil {
			// 	log.Errorf("The script error is executed after the first execution of dns check modification task, The script: %v ,err %v", conf.OtherScript, err)
			// } else {
			// 	log.Debugln("After the first execution of dns check modification task,the secript was executed successfully.")
			// 	log.Debugln(string(cmd))
			// }

		} else {
			log.Infof("continue ")
		}
	}

	// 然后执行定时任务获取ip，判断与记录ip是否相同，相同则继续监控，不同则修改dns信息，
	ticker := time.NewTicker(time.Duration(conf.TaskInterval) * time.Second)
	log.Infof("Perform tasks regularly, The Time interval(s) : %v", conf.TaskInterval)

	go func() {
		for {
			_ = <-ticker.C


			mynewip, err := getip.Process(*&conf.GetIps)
			if err != nil {
				log.Errorf("Get the public IP err: %v", err)
			} else {
				log.Infof("Get public ip success, IP: %+v", mynewip)
			}
			if mynewip != myip {
				ips := []string{mynewip}
				err = dns.DoneUp(conf, ips)
				if err != nil {
					log.Errorf("Execute dns to check and modify job errors : %v", err)
				} else if conf.OtherScript != "" {
                                        cmd := exec.Command(conf.OtherScript, ips[0])
                                        var out bytes.Buffer
                                        var stderr bytes.Buffer
                                        var input bytes.Buffer
                                        cmd.Stdout = &out
                                        cmd.Stderr = &stderr
			                cmd.Stdin = &input
                                        err = cmd.Run()
			                log.Infoln("args: ", cmd.Args)
			                log.Infoln("out: ",out.String())
			                log.Infoln("input: ",input.String())
			                log.Infoln("stderr: ",stderr.String())
				} else {
					log.Infof("continue ")
				}
				myip = mynewip
			}
		}
	}()

	for {
		time.Sleep(time.Second * 1)
	}

	// 并判断是否执行额外的脚本，是的话，就执行，否就继续执行定时任务

	// DNS修改逻辑
	// 通过域名查询域名信息，如果是顶级域名，修改顶级域名下所有的子域名ip，如果是子域名，只修改子域名的ip
}
